#include "fifo.h"
#include "btl_sdk_mass_production_test_protocol.h"

void sched_task_loop(void);
void uart0_putbyte(char a);
void test_uart0_sendbyte(unsigned char* packet, unsigned int size);
void uart0_sendbyte(unsigned char c);
extern unsigned char my_app_flag;

typedef struct test_struct {
    int en;
} test_t;

static test_t g_test_info;
test_t* test_info(void)
{
    return &g_test_info;
}

void uart0_receive_data(unsigned char* packet, unsigned int size)
{
    if (size == 0)
        return;

    fifo_t* fifo = fifo_info();
    for (unsigned int i = 0; i < size; ++i)
        fifo->write(packet[i]);

    /* 调度指纹任务 */
    sched_task_loop();
    // bf_print_d("====> rx len: %u", size);
    // test_uart0_sendbyte(packet, size);
}

void test_uart0_sendbyte(unsigned char* packet, unsigned int size)
{
    // char data[100];
    // snprintf(data, 100, "%x ", packet[0]);
    // unsigned int len = strlen(data);
    // for (unsigned int i = 0; i < len; ++i)
    //     uart0_sendbyte(data[i]);
    for (unsigned int i = 0; i < size; ++i)
        uart0_sendbyte(packet[i]);
}
void uart0_sendbyte(unsigned char c)
{
    uart0_putbyte(c);
}

struct bfxx_signature {
    unsigned char signature_data[2];
    unsigned char signature_len;
};

struct bfxx_signature sig;
unsigned char signature_check(unsigned char data)
{
    if (sig.signature_len == 0 && data == BTL_HEAD1) {
        sig.signature_data[0] = data;
        sig.signature_len = 1;
    } else if (sig.signature_len == 1 && data == BTL_HEAD2) {
        sig.signature_data[1] = data;
        sig.signature_len = 2;
    }

    if (sig.signature_len == 2 && sig.signature_data[0] == BTL_HEAD1 &&
        sig.signature_data[1] == BTL_HEAD2) {
        my_app_flag = 6;
    }
    return 0;
}

void bfxx_test_task(void)
{
    unsigned char data;
    fifo_t* fifo = fifo_info();
    for (;;) {
        int read_cnt = fifo->read(&data);
        if (read_cnt == 0)
            break;
        clr_wdt();
#if 0
        bf_print_d("====> rx: %x", data);
        test_uart0_sendbyte(&data, 1);
#endif
        signature_check(data);

        int r = btl_cmd_rx(data);
        if (r == BTL_TEST_PROTOCOL) {
            test_t* test = test_info();
            test->en = 1;
            sched_task_loop();
        }
    }

    btl_cmd_process();
}

int isTestEn(void)
{
    test_t* test = test_info();
    return test->en;
}
